package com.jinhuhang.u2.invertmodule;

import android.content.Intent;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.jinhuhang.u2.MyApplication;
import com.jinhuhang.u2.R;
import com.jinhuhang.u2.common.api.RetrofitUtils;
import com.jinhuhang.u2.common.base.activity.SimpleBaseActivity;
import com.jinhuhang.u2.common.constant.Constant;
import com.jinhuhang.u2.entity.Creaditor;
import com.jinhuhang.u2.entity.RasierVoucher;
import com.jinhuhang.u2.invertmodule.adapter.WelfareAdapter;
import com.jinhuhang.u2.myselfmodule.engine.user.UserActivity;
import com.jinhuhang.u2.ui.MainActivity;
import com.jinhuhang.u2.ui.customview.CustomToast;
import com.jinhuhang.u2.util.StringUtils;
import com.jinhuhang.u2.util.http.HttpWrapperList;
import com.jinhuhang.u2.util.http.ResultList;
import com.jinhuhang.u2.util.http.T;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by caoxiaowei on 2017/7/6.
 */
public class CreditorRightsTransferBuyActivity extends SimpleBaseActivity {



    WelfareAdapter mExperienceAdapter;
    boolean show = false;
    @Bind(R.id.back)
    ImageView mBack;
    @Bind(R.id.tv_title)
    TextView mTvTitle;
    @Bind(R.id.name_zz)
    TextView mNameZz;
    @Bind(R.id.yelid_zz)
    TextView mYelidZz;
    @Bind(R.id.month_zz)
    TextView mMonthZz;
    @Bind(R.id.type_zz)
    TextView mTypeZz;
    @Bind(R.id.money_zz)
    TextView mMoneyZz;
    @Bind(R.id.surpluses_zz)
    TextView mSurplusesZz;
    @Bind(R.id.img_buy)
    ImageView mImgBuy;
    @Bind(R.id.fulilay)
    LinearLayout mFulilay;
    @Bind(R.id.experiencelist1)
    ListView mExperiencelist;
    @Bind(R.id.laylist_zz)
    LinearLayout mLaylist;
    @Bind(R.id.zz_money)
    TextView mZzMoney;
    @Bind(R.id.comfirm)
    TextView mComfirm;

    String id = "0";

    Creaditor mCreaditor;
    @Bind(R.id.add_rare)
    TextView mAddRare;
    @Bind(R.id.zz_addmoney)
    TextView mZzAddmoney;

    @Nullable
    @OnClick({R.id.fulilay, R.id.back, R.id.comfirm})
    public void onclick(View view) {
        switch (view.getId()) {
            case R.id.fulilay:
                if (mBorrowBeen.size()==0){
                    CustomToast.showToast("没有可用福利！");
                    return;
                }
                if (show) {
                    show = false;
                    mImgBuy.setImageResource(R.drawable.touzi_tiaozhuan);
                    mExperiencelist.setVisibility(View.GONE);
                    mLaylist.setVisibility(View.GONE);
                } else {
                    show = true;
                    mImgBuy.setImageResource(R.drawable.touzi_downbutton_layout);
                    mExperiencelist.setVisibility(View.VISIBLE);
                    mLaylist.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.back:
                finish();
                break;
            case R.id.comfirm:
                checkToken();
                break;
        }
    }

    int jiaxiid, jiapos;
    String money,interest;
    @Override
    protected void initView() {
        super.initView();
        money=getIntent().getStringExtra("money");
        interest=getIntent().getStringExtra("interest");
        mCreaditor = (Creaditor) getIntent().getSerializableExtra("data");
        mAddRare.setVisibility(View.GONE);
        mZzMoney.setText(interest);
        id = mCreaditor.getBorrowId()+"";
        mTvTitle.setText("确认出借");
        mMoneyZz.setText(money+"元");
        mMonthZz.setText(mCreaditor.getRemainMsg());
        mNameZz.setText(mCreaditor.getTitle());
        mYelidZz.setText(mCreaditor.getApr()+"%");
        if (mCreaditor.getStyle() == 1) {
            mTypeZz.setText("先息后本");
        } else if (mCreaditor.getStyle() == 2) {
            mTypeZz.setText("到期本息");
        } else if (mCreaditor.getStyle() == 0) {
            mTypeZz.setText("等额本息");
        }
        mSurplusesZz.setText(MainActivity.userbean.getUseMoney()+"元");
        mExperienceAdapter = new WelfareAdapter(mBorrowBeen, this);
        mExperiencelist.setAdapter(mExperienceAdapter);
        mExperiencelist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (jiaxiid == 0) {
                    if (Double.parseDouble(money)<mBorrowBeen.get(position).getLowestAccount()){
                        CustomToast.showToast("投资金额不能低于该加息券可用金额！");
                        return;
                    }

                    getValue(position);
                    jiaxiid = mBorrowBeen.get(position).getId();
                    mBorrowBeen.get(position).setSelect(true);
                    mAddRare.setVisibility(View.VISIBLE);
                    if (mBorrowBeen.get(position).getInterestKey() == 0) {
                        mAddRare.setText("+" + mBorrowBeen.get(position).getFaceValue() + "%/" + mBorrowBeen.get(position).getInterestValue() + "天");
                    } else {
                        mAddRare.setText("+" + mBorrowBeen.get(position).getFaceValue() + "%/按标加息");
                    }

                } else {
                    if (jiapos == position) {
                        jiaxiid = 0;
                        mBorrowBeen.get(position).setSelect(false);
                        mAddRare.setVisibility(View.GONE);
                        mZzAddmoney.setText("+0");
                    } else {
                        getValue(position);
                        mAddRare.setVisibility(View.VISIBLE);
                        mBorrowBeen.get(jiapos).setSelect(false);
                        mBorrowBeen.get(position).setSelect(true);
                        if (mBorrowBeen.get(position).getInterestKey() == 0) {
                            mAddRare.setText("+" + mBorrowBeen.get(position).getFaceValue() + "%/" + mBorrowBeen.get(position).getInterestValue() + "天");
                        } else {
                            mAddRare.setText("+" + mBorrowBeen.get(position).getFaceValue() + "%/按标加息");
                        }
                    }
                }
                jiapos = position;

                mExperienceAdapter.notifyDataSetChanged();

            }
        });
    }

    //加息券计算利息
    private void getValue(int pos) {
        double result =StringUtils.isEmpty(mBorrowBeen.get(pos).getFaceValue())?0:Double.parseDouble(mBorrowBeen.get(pos).getFaceValue());
        double invert =StringUtils.isEmpty(money)?0:Double.parseDouble(money);

        long start= StringUtils.isEmpty(mBorrowBeen.get(pos).getEffectiveDateStart())?0:Long.parseLong(mBorrowBeen.get(pos).getEffectiveDateStart());
        long end=StringUtils.isEmpty(mBorrowBeen.get(pos).getEffectiveDateEnd())?0:Long.parseLong(mBorrowBeen.get(pos).getEffectiveDateEnd());
        Log.i("wwwwww"+(end-start),(end-start)/1000+"----"+((end-start)/1000/(60*60*24)));
        if ((end-start)>0){
            double re=invert*(result/100)*((end-start)/1000/(60*60*24))/365;
            mZzAddmoney.setText("+"+String.format("%.2f", re));
        }else {
            mZzAddmoney.setText("+0");
        }
    }

    int pageNo = 1;
    int pageSize = 15;
    List<RasierVoucher> mBorrowBeen = new ArrayList<>();

    //可用福利
    @Override
    protected void initData() {
        super.initData();
//        Map<String, Integer> map = new HashMap<>();
//        map.put("type", 5);
//        map.put("userId", Integer.parseInt(MainActivity.uid));
//        map.put("pageNo", pageNo);
//        map.put("pageSize", pageSize);
//        addSubscription(RetrofitUtils.getInstance().build()
//                .welfareLst(map)
//                .compose(T.defaultScheduler())
//                .subscribe(new ResultList<HttpWrapperList<RasierVoucher>>() {
//                    @Override
//                    protected void onSuccess(HttpWrapperList<RasierVoucher> data) {
//
//                        mBorrowBeen.addAll(data.getData());
//                        mExperienceAdapter.notifyDataSetChanged();
//                    }
//                }));
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_creditor_buy;
    }

    private void checkToken(){
        addSubscription(RetrofitUtils.getInstance().build()
                .checkToken(MainActivity.userbean.getUserId(),MainActivity.userbean.getToken())
                .compose(T.defaultScheduler())
                .subscribe(new ResultList<HttpWrapperList<String>>() {

                    @Override
                    protected void onSuccess(HttpWrapperList<String> o) {
                        if (o.getCode()==200){
                            buy();
                            MainActivity.checktoken=true;
                        }else {
                            //token 失效
                            MainActivity.checktoken=false;
                            MainActivity.tip=null;
                            if (o.getCode()!=301) {
                                MainActivity.tip=o.getInfo();
                            }
                            if (MainActivity.tip!=null) {
                                CustomToast.showToast(MainActivity.tip);
                            }
                            Intent intent=new Intent(MyApplication.getContext(), UserActivity.class);
                            intent.putExtra("type",UserActivity.LOGIN);
                            startActivity(intent);
                            finish();
                        }
                    }

                }));
    }
    private long exitTime = 0l;
    boolean click=false;
    private void buy() {
        if (click)return;
        if ((System.currentTimeMillis() - exitTime) > 3000) {
            exitTime = System.currentTimeMillis();
        }else {
            return;
        }
        showDialog(null);
        Intent intent = new Intent(this, ResultActivity.class);
        intent.putExtra("type", Constant.tender_success);
        intent.putExtra("title", mCreaditor.getTitle());
        intent.putExtra("apr", mCreaditor.getApr()+"");
        intent.putExtra("term", mCreaditor.getRemainMsg()+"");
        intent.putExtra("money", money);
        if (jiaxiid!=0){
            intent.putExtra("jiaxi", String.valueOf(mBorrowBeen.get(jiapos).getFaceValue()));
        }
        Map<String, String> map = new HashMap<>();
        map.put("userId", MainActivity.uid);
        map.put("source", String.valueOf(3));
        map.put("borrowId", String.valueOf(mCreaditor.getBorrowId()));
        map.put("investMoney", money);
        map.put("aprCouponId", String.valueOf(jiaxiid));
        map.put("moneyCouponId", "");//债转标没有抵扣券
        click=true;
        addSubscription(RetrofitUtils.getInstance().build()
                .croditorTenderInvert(map)
                .compose(T.defaultScheduler())
                .subscribe(new ResultList<HttpWrapperList<Creaditor>>() {

                    @Override
                    protected void onSuccess(HttpWrapperList<Creaditor> data) {
                        if (data.code == Constant.SUCCESS_CODE) {
                            intent.putExtra(ResultActivity.typestr, Constant.tender_success);
                        } else {
                            intent.putExtra(ResultActivity.typestr, Constant.tender_fail);
                        }
                        dissDialog();
                        startActivity(intent);
                    }
                }));
    }
}
